"""
配置管理模块
"""

import json
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Tuple, Optional


@dataclass
class UIConfig:
    """用户界面配置"""
    window_size: Tuple[int, int] = (1000, 800)
    window_min_size: Tuple[int, int] = (800, 600)
    thumbnail_width: int = 220
    max_thumbnail_columns: int = 5
    theme: str = "default"
    language: str = "zh_CN"


@dataclass
class ProcessingConfig:
    """处理配置"""
    max_concurrent_operations: int = 3
    thumbnail_quality: int = 85
    default_output_format: str = "pdf"
    auto_save_config: bool = True
    temp_dir: str = "temp"


@dataclass
class LogConfig:
    """日志配置"""
    log_level: str = "INFO"
    log_to_file: bool = True
    log_to_console: bool = True
    max_log_files: int = 10
    log_file_size_mb: int = 10


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = "config.json"):
        self.config_file = Path(config_file)
        self.ui = UIConfig()
        self.processing = ProcessingConfig()
        self.log = LogConfig()
        
        # 创建配置目录
        self.config_file.parent.mkdir(parents=True, exist_ok=True)
        
        # 加载配置
        self.load_config()
    
    def load_config(self) -> bool:
        """从文件加载配置"""
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 更新UI配置
                if 'ui' in data:
                    ui_data = data['ui']
                    # 转换列表为元组（JSON中的数组会被加载为列表）
                    if 'window_size' in ui_data and isinstance(ui_data['window_size'], list):
                        ui_data['window_size'] = tuple(ui_data['window_size'])
                    if 'window_min_size' in ui_data and isinstance(ui_data['window_min_size'], list):
                        ui_data['window_min_size'] = tuple(ui_data['window_min_size'])

                    self.ui = UIConfig(**{k: v for k, v in ui_data.items()
                                        if k in UIConfig.__dataclass_fields__})
                
                # 更新处理配置
                if 'processing' in data:
                    proc_data = data['processing']
                    self.processing = ProcessingConfig(**{k: v for k, v in proc_data.items() 
                                                        if k in ProcessingConfig.__dataclass_fields__})
                
                # 更新日志配置
                if 'log' in data:
                    log_data = data['log']
                    self.log = LogConfig(**{k: v for k, v in log_data.items() 
                                          if k in LogConfig.__dataclass_fields__})
                
                return True
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            return False
        
        return False
    
    def save_config(self) -> bool:
        """保存配置到文件"""
        try:
            config_data = {
                'ui': asdict(self.ui),
                'processing': asdict(self.processing),
                'log': asdict(self.log)
            }
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, indent=2, ensure_ascii=False)
            
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def reset_to_defaults(self):
        """重置为默认配置"""
        self.ui = UIConfig()
        self.processing = ProcessingConfig()
        self.log = LogConfig()
        
        if self.processing.auto_save_config:
            self.save_config()
    
    def get_temp_dir(self) -> Path:
        """获取临时目录路径"""
        temp_dir = Path(self.processing.temp_dir)
        temp_dir.mkdir(exist_ok=True)
        return temp_dir
